package com.bauer.base.concurrent;

import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author ：rui.wei
 * @Date ：Created in 15:20 2019/6/3
 * @Description：
 */
public class ThreadPoolUtil {

    private static ExecutorService executor = new ThreadPoolExecutor(100, 200, 600, TimeUnit.MILLISECONDS,
            new LinkedBlockingDeque<>());


    public static void execute(Runnable runnable) {
        executor.execute(runnable);
    }

    /**
     * @param times 执行次数
     */
    public static void executeTimes(Runnable runnable, int times) {
        executeTimes(runnable, times, null);
    }

    public static void executeTimes(Runnable runnable, int times, ThreadShutdownCallback threadShutdownCallback) {
        for (int i = 0; i < times; i++) {
            executor.execute(runnable);
        }
        executor.shutdown();
        while (true) {
            if (executor.isTerminated() && threadShutdownCallback != null) {
                threadShutdownCallback.call();
                break;
            }
        }
    }

    public static <T> Future<T> submit(Callable<T> callable) {
        return executor.submit(callable);
    }

}
